package com.uinnova.product.eam.init.schedule.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uinnova.product.eam.init.iam.SyncIAMUserSvc;
import com.uinnova.product.eam.service.asset.BmConfigSvc;
import com.uinnova.project.base.diagram.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: 国投IAM用户同步定时任务
 * @author: LiMG
 * @create: 2024-06-05 10:27:14
 **/
@Component
@Log4j2
public class IAMUserSyncJob extends QuartzJobBean {

    @Autowired
    private BmConfigSvc bmConfigSvc;

    @Value("${http.resource.space}")
    private String httpPath;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SyncIAMUserSvc syncIAMUserSvc;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        /**
         * 从视图配置中获取配置信息
         */
        String config = bmConfigSvc.getConfigType("IAM_USER_SYNC_CONFIG");
        if (StrUtil.isEmpty(config)) {
            log.error("无法获取IAM用户同步视图配置项");
            return;
        }
        JSONObject jsonConfig = JSON.parseObject(config);
        // 获取任务开启状态
        Boolean openFlag = jsonConfig.getBoolean("openFlag");
        if (!openFlag) {
            log.error("IAM用户同步任务未开启");
            return;
        }
        // 获取同步锁
        String key = "lock:syncIAMUserDataSync:" + httpPath.replace(":", "");
        boolean lock = redisUtil.setnx(key, "1", 60, TimeUnit.SECONDS);
        if(!lock){
            log.info("获取锁失败");
            return;
        }
        try {
            syncIAMUserSvc.syncUserData(jsonConfig);
        } catch (Exception e) {
            log.error("IAM用户数据同步失败: {}", e.getMessage(), e);
        } finally {
            // 删除同步锁
            redisUtil.del(key);
        }
    }
}
